import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *



def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)



def _Find_input_element(driver:WebDriver,label:str) -> WebElement:
    anchor_element = driver.find_elements(by=By.XPATH,value=f"//*[(self::span or self::label or self::div) and text()='{label}']")
    if len(anchor_element) == 1:
        find_xpath_path = "./parent::*//input"
        while True:
            try:
                element = anchor_element[0].find_element(by=By.XPATH,value=find_xpath_path)
                return element
            except NoSuchElementException:
                print(f"提示 : 当前层级没有找到 Input 元素,继续向上查找!")
                find_xpath_path = find_xpath_path.replace("//input","/parent::*//input")
                continue




def On_InputPage_Input_Batch_Price_And_Code(driver:WebDriver,Stock:int,Price:float,Code:str) -> None:
    
    # 1.填写库存
    try:
        Batch_Price_Input_Element_Xpath = f"//input[@placeholder='库存']"
        element = driver.find_element(by=By.XPATH,value=Batch_Price_Input_Element_Xpath)
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while True:
            if(element.get_attribute("value") == ""):
                break
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Stock)
    except NoSuchElementException:
        print("提示 : 没有找到批量价格输入框!")
        
    # 2.填写价格
    try:
        Batch_Price_Input_Element_Xpath = f"//input[@placeholder='拼单价']"
        element = driver.find_element(by=By.XPATH,value=Batch_Price_Input_Element_Xpath)
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while True:
            if(element.get_attribute("value") == ""):
                break
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Price)
    except NoSuchElementException:
        print("提示 : 没有找到批量价格输入框!")
    
    try:
        Batch_Price_Input_Element_Xpath = f"//input[@placeholder='单买价']"
        element = driver.find_element(by=By.XPATH,value=Batch_Price_Input_Element_Xpath)
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while True:
            if(element.get_attribute("value") == ""):
                break
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Price + 20)
    except NoSuchElementException:
        print("提示 : 没有找到批量价格输入框!")
    
    # 3.填写编码
    try:
        Batch_Price_Input_Element_Xpath = f"//input[@placeholder='规格编码']"
        element = driver.find_element(by=By.XPATH,value=Batch_Price_Input_Element_Xpath)
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while True:
            if(element.get_attribute("value") == ""):
                break
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Code)
    except NoSuchElementException:
        print("提示 : 没有找到编码输入框!")

    # 4.批量设置
    try:
        element = driver.find_element(by=By.XPATH,value=f"//button[not(contains(@class,'disabled'))]/span[text()='批量设置']")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except NoSuchElementException:
        print(f"提示 : 没有找到批量设置的按钮!")


    # 5.设置商品编码
    try:
        element = _Find_input_element(driver,"商品编码")
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while True:
            if(element.get_attribute("value") == ""):
                break
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Code)
    except NoSuchElementException:
        print("提示 : 没有找到商品编码输入框!")